package myJs.components

import japgolly.scalajs.react._
import japgolly.scalajs.react.component.Scala.BackendScope
import japgolly.scalajs.react.extra.StateSnapshot
import japgolly.scalajs.react.vdom.all._
import myJs.Implicits._
import myJs.myPkg.jquery._
import myJs.tool.Tool
import org.scalajs.dom.html

import scala.collection.immutable.SeqMap

/**
 * Created by yz on 3/11/2020
 */
object PureSelectComponent {

  case class Props(state: StateSnapshot[String], name: String, optionMap: SeqMap[String, String]) {
    @inline def render: VdomElement = {
      Component(this)
    }
  }

  class Backend(bs: BackendScope[Props, Unit]) {

    private val inputRef = Ref[html.Select]

    def didMount = {
      inputRef.foreach { y =>
        Tool.popover
      }
    }

    def unmount = {
      inputRef.foreach { y =>
      }
    }

    def didUpdate(p: Props) = {
      inputRef.foreach { y =>
      }
    }

    def render(p: Props) = {

      def valueChange(e: ReactEventFromInput) = {
        val myValue = e.target.value
        p.state.modState(x => myValue)
      }

      val s = p.state.value
      select(`class` := "form-control", name := s"${p.name}", value := s"${s}", onChange ==> valueChange,
        p.optionMap.toVdomArray { case (v, text) =>
          option(key:=s"${text}",value := s"${v}", s"${text}")
        }
      ).withRef(inputRef)
    }

  }

  val Component = ScalaComponent.builder[Props].renderBackend[Backend].
    componentDidMount(x => x.backend.didMount).componentWillUnmount(_.backend.unmount).
    componentDidUpdate(x => x.backend.didUpdate(x.currentProps)).
    build

}



